<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <div class="text item">
      <el-form :model="pass" :rules="passRules" ref="passRef" label-width="100px">
        <!-- 第一项：原密码 -->
        <el-form-item label="原密码" prop="old_pwd">
          <el-input v-model="pass.old_pwd"></el-input>
        </el-form-item>
        <!-- 第二项：新密码 -->
        <el-form-item label="新密码" prop="new_pwd">
          <el-input v-model="pass.new_pwd"></el-input>
        </el-form-item>
        <!-- 第三项：确认新密码 -->
        <el-form-item label="确认新密码" prop="re_pwd">
          <el-input v-model="pass.re_pwd"></el-input>
        </el-form-item>
        <!-- 第四项：按钮 -->
        <el-form-item>
          <el-button type="primary" @click="updatePwd">确认修改</el-button>
          <el-button @click="$refs.passRef.resetFields()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { updatePwdAPI } from '@/api/reg.js'

export default {
  data() {
    const guize1 = (rule, value, callback) => {
      // 这个guize1，新密码这个输入框使用了；所以value表示新密码
      if (value === this.pass.old_pwd) {
        callback(new Error('新密码不能和原密码一致'))
      } else {
        callback()
      }
    }
    const guize2 = (rule, value, callback) => {
      // 这个guize2，确认新密码这个输入框使用了；所以value表示 确认新密码
      if (value === this.pass.new_pwd) {
        callback()
      } else {
        callback(new Error('两次密码不一致'))
      }
    }
    return {
      // 定义数据项
      pass: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      // 定义验证规则
      passRules: {
        old_pwd: [
          { required: true, message: '原密码必填', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '6~15位的非空字符', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '原密码必填', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '6~15位的非空字符', trigger: 'blur' },
          { validator: guize1, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '原密码必填', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '6~15位的非空字符', trigger: 'blur' },
          { validator: guize2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updatePwd() {
      this.$refs.passRef.validate(async valid => {
        if (valid) {
          // 表示验证通过
          const { data: res } = await updatePwdAPI(this.pass)
          if (res.code === 0) {
            this.$message.success(res.message) // 提示
            this.$refs.passRef.resetFields() // 重置表单
          } else {
            this.$message.error(res.message)
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  font-size: 13px;
}

.el-form {
  width: 500px;
}
</style>
